package com.fox.stock.security.service;

import com.fox.stock.mapper.SysRoleMapper;
import com.fox.stock.mapper.SysUserMapper;
import com.fox.stock.mapper.SysUserRoleMapper;
import com.fox.stock.pojo.domain.PermissionDomain;
import com.fox.stock.pojo.entity.SysPermission;
import com.fox.stock.pojo.entity.SysRole;
import com.fox.stock.pojo.entity.SysUser;
import com.fox.stock.security.util.PermissionTreeUtil;
import com.fox.stock.security.vo.LoginUserDetail;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class LoginUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        SysUser sysUser = sysUserMapper.selectByUsernameSysUser(s);
        // 判断用户是否存在或合法
        if (sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        // 用户合法,封装UserDetails类(因为官方的UserDetails类不能满足业务需求,故要定一个类去实现UserDetails类)
        // 根据用户id查询当前用户拥有的权限集合
        List<SysPermission> list = sysUserMapper.getUserPermissions(sysUser.getId());
        // 查询权限树和菜单按钮集合
        // 菜单
        List<String> permissions = PermissionTreeUtil.getPermissions(list);
        // 权限
        List<PermissionDomain> menus = PermissionTreeUtil.getMenus(list);
        // 获取用户拥有的角色
        List<SysRole> roles = sysRoleMapper.getRoleByUserId(sysUser.getId());
        // 将用户的权限标识和角色标识维护到权限集合中
        List<String> perms = new ArrayList<>();
        list.stream().forEach(per ->{
            if (StringUtils.isNotBlank(per.getPerms())) {
                perms.add(per.getPerms());
            }
        });
        roles.stream().forEach(role -> {
            perms.add("ROLE_"+role.getName());
        });
        String[] permStr = perms.toArray(new String[perms.size()]);
        // 将用户权限标识转化为权限对象集合
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(permStr);
        // 封装详细信息实体对象
        LoginUserDetail loginUserDetail = new LoginUserDetail();
        BeanUtils.copyProperties(sysUser,loginUserDetail);
        loginUserDetail.setMenus(menus);
        loginUserDetail.setPermissions(permissions);
        loginUserDetail.setAuthorities(authorityList);


        return loginUserDetail;
    }
}